/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.lswms.modules.job.task;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lswms.modules.lswms.Constant.TaskConstant;
import com.lswms.modules.lswms.Constant.TradeConstant;
import com.lswms.modules.lswms.dao.check.CheckdetailDao;
import com.lswms.modules.lswms.dao.orders.OrderdetaillistDao;
import com.lswms.modules.lswms.dao.recipient.RecipientsDao;
import com.lswms.modules.lswms.dao.stock.InventoryDao;
import com.lswms.modules.lswms.dao.stock.TradeDao;
import com.lswms.modules.lswms.dao.stock.TrayDao;
import com.lswms.modules.lswms.dao.task.TaskDao;
import com.lswms.modules.lswms.entity.check.CheckdetailEntity;
import com.lswms.modules.lswms.entity.orders.OrderdetaillistEntity;
import com.lswms.modules.lswms.entity.recipient.RecipientsEntity;
import com.lswms.modules.lswms.entity.stock.InventoryEntity;
import com.lswms.modules.lswms.entity.stock.TradeEntity;
import com.lswms.modules.lswms.entity.stock.TrayEntity;
import com.lswms.modules.lswms.entity.task.TaskEntity;
import com.lswms.modules.lswms.service.base.SequenceService;
import com.lswms.modules.lswms.service.task.TaskService;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.extern.slf4j.Slf4j;

/**
 * 扫描完成任务
 */
@Component("WCS2WMSTask")
@DisallowConcurrentExecution
@Slf4j
public class WCS2WMSTask implements ITask {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TaskDao taskDao;

	@Autowired
	private TradeDao tradeDao;

	@Autowired
	private TaskService taskService;

	@Autowired
	private InventoryDao inventoryDao;

	@Autowired
	private SequenceService sequenceService;

	@Autowired
	private OrderdetaillistDao orderdetaillistDao;
	@Autowired
	private RecipientsDao recipientsDao;

	@Autowired
	private CheckdetailDao checkdetailDao;

	@Autowired
	private TrayDao trayDao;

	@Autowired
	private PlatformTransactionManager txManager;

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public void run(String params) {
		logger.debug("TaskTask定时任务正在执行，参数为：{}", params);

		DefaultTransactionDefinition def = new DefaultTransactionDefinition();

		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务

		TransactionStatus status = null; // 获得事务状态

		// 读取WCS完成的任务，更新WMS的库存
		List<Map<String, Object>> list = taskDao.getWCSDoneTask();
		for (Map<String, Object> map : list) {
			try {
				status = txManager.getTransaction(def);

				Integer task_id = (Integer) map.get("task_id");
				Integer priority = (Integer) map.get("priority");
				Integer tasktype = map.get("task_type") == null ? null : (Integer) map.get("task_type");
				Integer taskstatus = (Integer) map.get("task_status");
				String fromlocation = (String) map.get("locate_from");
				String tolocation = (String) map.get("locate_to");
				String fromtray = (String) map.get("tary_from");
				String totray = (String) map.get("tary_to");
				Integer fromlane = (Integer) map.get("fromlane");
				String fromrow = (String) map.get("GETX");
				String fromcolumn = (String) map.get("GETY");
				String fromlevel = (String) map.get("GETZ");
				Integer tolane = (Integer) map.get("tolane");
				String torow = (String) map.get("PUTX");
				String tocolumn = (String) map.get("PUTY");
				String tolevel = (String) map.get("PUTZ");
				String weight = (String) map.get("weigth");

				// 按托盘完成任务，物料跟随托盘移库

				// 查询WMS的任务 ,取集合的第一个任务的目的库位为整个托盘的目的库位
				QueryWrapper<TaskEntity> taskEntityQuery = new QueryWrapper<TaskEntity>();
				taskEntityQuery.eq("taskno", task_id);
				taskEntityQuery.eq("sendflag", 5);
				taskEntityQuery.lt("status", 9);
//				if (tasktype.equals("2")){
//					taskEntityQuery.lt("status", 7);//************************原本是小于9，现在wcs任务要提前完成
//				}else {
//					taskEntityQuery.lt("status", 9);//************************原本是小于9，现在wcs任务要提前完成43
//				}

				List<TaskEntity> Tasklist = taskDao.selectList(taskEntityQuery);
				if (Tasklist == null || Tasklist.size() == 0) {
					// 将任务记录写入备份库
//					taskDao.insertRecord(map);
//					// 删除WMS已做完的任务
//					taskDao.deleteWCSTask(map);
//
//					txManager.commit(status);
					txManager.commit(status);
					continue;
				}

				// 添加托盘重量记录
				BigDecimal weightBig = BigDecimal.ZERO;
				try {
					weightBig = new BigDecimal(weight);
				} catch (Exception e) {
					weightBig = BigDecimal.ZERO;
				}

				QueryWrapper<TrayEntity> trayQuery = new QueryWrapper<TrayEntity>();
				trayQuery.eq("tray", fromtray);
				TrayEntity trayEntity = trayDao.selectOne(trayQuery);
				if (trayEntity == null) {
					TrayEntity insertTray = new TrayEntity();
					insertTray.setTray(fromtray);
					insertTray.setWeigth(weightBig);
					trayDao.insert(insertTray);
				} else {
					TrayEntity updateTray = new TrayEntity();
					updateTray.setWeigth(weightBig);

					UpdateWrapper<TrayEntity> trayUpdate = new UpdateWrapper<TrayEntity>();
					trayUpdate.eq("tray", fromtray);
					trayDao.update(updateTray, trayUpdate);
				}

				TaskEntity firstTaskEntity = Tasklist.get(0);
				String firsttolocation = firstTaskEntity.getTolocation();
				// 查寻托盘的库存，将托盘转移至新的库位
				QueryWrapper<InventoryEntity> inventoryQuery = new QueryWrapper<InventoryEntity>();
				inventoryQuery.eq("tray", fromtray);
				inventoryQuery.eq("location", fromlocation);
				inventoryQuery.ge("qty", 0);

				List<InventoryEntity> inventoryEntityList = inventoryDao.selectList(inventoryQuery);
				for (InventoryEntity inventoryEntity : inventoryEntityList) {
					// 设置库存变动
					// toloc的库位增加库存
					QueryWrapper<InventoryEntity> inventoryTolocQuery = new QueryWrapper<InventoryEntity>();
					inventoryTolocQuery.eq("sku", inventoryEntity.getSku());
					inventoryTolocQuery.eq("location", firsttolocation);
					inventoryTolocQuery.eq("lot", inventoryEntity.getLot());
					inventoryTolocQuery.eq("tray", inventoryEntity.getTray());
					inventoryTolocQuery.eq("box", inventoryEntity.getBox());
					InventoryEntity inventoryEntityToloc = inventoryDao.selectOne(inventoryTolocQuery);
					if (inventoryEntityToloc == null) {
						// 库存记录不存在，增加库存记录
						InventoryEntity inventoryTolocInsert = new InventoryEntity();
						inventoryTolocInsert.setSku(inventoryEntity.getSku());
						inventoryTolocInsert.setLocation(firsttolocation);
						inventoryTolocInsert.setLot(inventoryEntity.getLot());
						inventoryTolocInsert.setTray(inventoryEntity.getTray());
						inventoryTolocInsert.setBox(inventoryEntity.getBox());
						inventoryTolocInsert.setQty(inventoryEntity.getQty());
						inventoryTolocInsert.setPickqty(inventoryEntity.getPickqty());
						inventoryTolocInsert.setPutqty(inventoryEntity.getPutqty());
						inventoryTolocInsert.setStatus(0);
						inventoryDao.insert(inventoryTolocInsert);
					} else {
						UpdateWrapper<InventoryEntity> inventoryTolocUpdate = new UpdateWrapper<InventoryEntity>();
						inventoryTolocUpdate.eq("sku", inventoryEntityToloc.getSku());
						inventoryTolocUpdate.eq("location", inventoryEntityToloc.getLocation());
						inventoryTolocUpdate.eq("lot", inventoryEntityToloc.getLot());
						inventoryTolocUpdate.eq("tray", inventoryEntityToloc.getTray());
						inventoryTolocUpdate.eq("box", inventoryEntityToloc.getBox());

						InventoryEntity updateInventory = new InventoryEntity();
						updateInventory.setQty(inventoryEntityToloc.getQty().add(inventoryEntity.getQty()));
						updateInventory.setPickqty(inventoryEntityToloc.getPickqty().add(inventoryEntity.getPickqty()));
						updateInventory
								.setPutqty(inventoryEntityToloc.getPutqty().subtract(inventoryEntity.getPutqty()));
						inventoryDao.update(updateInventory, inventoryTolocUpdate);
					}

//				// fromloc 的库位减库存，

					UpdateWrapper<InventoryEntity> inventoryFormlocUpdate = new UpdateWrapper<InventoryEntity>();
					inventoryFormlocUpdate.eq("sku", inventoryEntity.getSku());
					inventoryFormlocUpdate.eq("location", inventoryEntity.getLocation());
					inventoryFormlocUpdate.eq("lot", inventoryEntity.getLot());
					inventoryFormlocUpdate.eq("tray", inventoryEntity.getTray());
					inventoryFormlocUpdate.eq("box", inventoryEntity.getBox());
					inventoryFormlocUpdate.set("qty", inventoryEntity.getQty().subtract(inventoryEntity.getQty()));
					inventoryFormlocUpdate.set("pickqty",
							inventoryEntity.getPickqty().subtract(inventoryEntity.getPickqty()));
					inventoryFormlocUpdate.set("putqty",
							inventoryEntity.getPutqty().subtract(inventoryEntity.getPutqty()));
					inventoryDao.update(null, inventoryFormlocUpdate);

					// 增加交易信息
					String tradekey = sequenceService.getSequence("trade");
					TradeEntity tradeEntity = new TradeEntity();

					tradeEntity.setTradekey(tradekey);
					tradeEntity.setTradetype(TradeConstant.TRADETYPE_MV);
					tradeEntity.setSku(inventoryEntity.getSku());
					tradeEntity.setQty(inventoryEntity.getQty());
					tradeEntity.setSourcetype(TradeConstant.SOURCETYPE_MOVE);
					tradeEntity.setSourcekey(task_id + "");
					tradeEntity.setSourceline(null);
					tradeEntity.setSourcelinelist(null);
					tradeEntity.setFromlocation(inventoryEntity.getLocation());
					tradeEntity.setTolocation(firsttolocation);
					tradeEntity.setFromtray(inventoryEntity.getTray());
					tradeEntity.setTotray(inventoryEntity.getTray());
					tradeEntity.setFrombox(inventoryEntity.getBox());
					tradeEntity.setTobox(inventoryEntity.getBox());
					tradeEntity.setFromlot(inventoryEntity.getLot());
					tradeEntity.setTolot(inventoryEntity.getLot());
					tradeEntity.setFromlot1(null);
					tradeEntity.setFromlot2(null);
					tradeEntity.setFromlot3("");
					tradeEntity.setFromlot4("");
					tradeEntity.setFromlot5("");
					tradeEntity.setFromlot6("");
					tradeEntity.setFromlot7("");
					tradeEntity.setFromlot8("");
					tradeEntity.setFromlot9("");
					tradeEntity.setFromlot10("");
					tradeEntity.setFromlot11("");
					tradeEntity.setFromlot12("");
					tradeEntity.setFromlot13("");
					tradeEntity.setFromlot14("");
					tradeEntity.setFromlot15("");
					tradeEntity.setTolot1(null);
					tradeEntity.setTolot2(null);
					tradeEntity.setTolot3("");
					tradeEntity.setTolot4("");
					tradeEntity.setTolot5("");
					tradeEntity.setTolot6("");
					tradeEntity.setTolot7("");
					tradeEntity.setTolot8("");
					tradeEntity.setTolot9("");
					tradeEntity.setTolot10("");
					tradeEntity.setTolot11("");
					tradeEntity.setTolot12("");
					tradeEntity.setTolot13("");
					tradeEntity.setTolot14("");
					tradeEntity.setTolot15("");
					tradeEntity.setRemark("WCS");
					tradeDao.insert(tradeEntity);
				}

				// 查询该托盘所有未完成的任务
				QueryWrapper<TaskEntity> taskEntityQuery1 = new QueryWrapper<TaskEntity>();
				taskEntityQuery1.eq("fromtray", fromtray);
				taskEntityQuery1.lt("status", 9);
//				if (tasktype.equals("2")){
//					taskEntityQuery1.lt("status", 7);//************************原本是小于9，现在wcs任务要提前完成
//				}else {
//					taskEntityQuery1.lt("status", 9);//************************原本是小于9，现在wcs任务要提前完成43
//				}

				List<TaskEntity> Tasklist1 = taskDao.selectList(taskEntityQuery1);
				for (TaskEntity TaskEntity : Tasklist1) {
					if (TaskEntity.getTasktype().equals(TaskConstant.TASK_PICK)) {
						// 如果是出库任务，变更拣货明细的当前库位信息
						UpdateWrapper<OrderdetaillistEntity> orderdetaillistUpdate = new UpdateWrapper<OrderdetaillistEntity>();
						orderdetaillistUpdate.eq("orderkey", TaskEntity.getSourcekey());
						orderdetaillistUpdate.eq("line", TaskEntity.getSourceline());
						orderdetaillistUpdate.eq("linelist", TaskEntity.getSourcelinelist());
						orderdetaillistUpdate.set("loc", firsttolocation);
						orderdetaillistUpdate.set("tray", TaskEntity.getTotray());
						orderdetaillistUpdate.set("box", TaskEntity.getTobox());
						orderdetaillistUpdate.set("actqty", TaskEntity.getQty());
						orderdetaillistDao.update(null, orderdetaillistUpdate);
					}
					if (TaskEntity.getTasktype().equals(TaskConstant.TASK_PY)) {
						// 如果是出库任务，变更拣货明细的当前库位信息
						UpdateWrapper<RecipientsEntity> RecipientsEntityUpdate = new UpdateWrapper<RecipientsEntity>();
						RecipientsEntityUpdate.eq("recipientkey", TaskEntity.getSourcekey());
						RecipientsEntityUpdate.set("loc", firsttolocation);
						RecipientsEntityUpdate.set("tray", TaskEntity.getTotray());
						RecipientsEntityUpdate.set("box", TaskEntity.getTobox());
						RecipientsEntityUpdate.set("qty", TaskEntity.getQty());
						recipientsDao.update(null, RecipientsEntityUpdate);
					}

					if (TaskEntity.getTasktype().equals(TaskConstant.TASK_PA)) {

						// 更改目的库位的库存
						QueryWrapper<InventoryEntity> inventoryTolocQuery1 = new QueryWrapper<InventoryEntity>();
						inventoryTolocQuery1.eq("sku", TaskEntity.getSku());
						inventoryTolocQuery1.eq("location", firsttolocation);
						inventoryTolocQuery1.eq("lot", TaskEntity.getFromlot());
						inventoryTolocQuery1.eq("tray", TaskEntity.getFromtray());
						inventoryTolocQuery1.eq("box", TaskEntity.getFrombox());
						InventoryEntity inventoryEntityToloc = inventoryDao.selectOne(inventoryTolocQuery1);
//					if (inventoryEntityToloc.getPutqty().compareTo(TaskEntity.getQty()) < 0) {
//						// 回滚事务
//						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//						return MEGConstant.INVENTORY_PICKQTY_NOT_MATCH_TASK_ACTQTY;
//					}
						if (inventoryEntityToloc != null) {
							UpdateWrapper<InventoryEntity> updateInventory = new UpdateWrapper<InventoryEntity>();
							updateInventory.eq("sku", TaskEntity.getSku());
							updateInventory.eq("location", firsttolocation);
							updateInventory.eq("lot", TaskEntity.getFromlot());
							updateInventory.eq("tray", TaskEntity.getFromtray());
							updateInventory.eq("box", TaskEntity.getFrombox());
							InventoryEntity updateInventoryEntity = new InventoryEntity();

							updateInventoryEntity
									.setPutqty(inventoryEntityToloc.getPutqty().subtract(TaskEntity.getQty()));

							inventoryDao.update(updateInventoryEntity, updateInventory);
						}
					}
					if (TaskEntity.getTasktype().equals(TaskConstant.TASK_CC)) {
						// 如果是出库任务，变更拣货明细的当前库位信息
						UpdateWrapper<CheckdetailEntity> checkdetailUpdate = new UpdateWrapper<CheckdetailEntity>();
						checkdetailUpdate.eq("checkkey", TaskEntity.getSourcekey());
						checkdetailUpdate.eq("line", TaskEntity.getSourceline());

						checkdetailUpdate.set("toloc", firsttolocation);

						checkdetailDao.update(null, checkdetailUpdate);
					}
					// 空箱移出库后直接扣减库存
					if (TaskEntity.getTasktype().equals(TaskConstant.TASK_MV) && TaskEntity.getSku().equals("KX")
							&& TaskEntity.getTolocation().equalsIgnoreCase("PICK")) {

						QueryWrapper<InventoryEntity> inventoryTolocQuery = new QueryWrapper<InventoryEntity>();
						inventoryTolocQuery.eq("sku", TaskEntity.getSku());
						inventoryTolocQuery.eq("location", TaskEntity.getTolocation());
						inventoryTolocQuery.eq("lot", TaskEntity.getFromlot());
						inventoryTolocQuery.eq("tray", TaskEntity.getFromtray());
						inventoryTolocQuery.eq("box", TaskEntity.getFrombox());
						InventoryEntity inventoryEntity = inventoryDao.selectOne(inventoryTolocQuery);
						if (inventoryEntity != null) {
							UpdateWrapper<InventoryEntity> inventoryTolocUpdate = new UpdateWrapper<InventoryEntity>();
							inventoryTolocUpdate.eq("sku", inventoryEntity.getSku());
							inventoryTolocUpdate.eq("location", inventoryEntity.getLocation());
							inventoryTolocUpdate.eq("lot", inventoryEntity.getLot());
							inventoryTolocUpdate.eq("tray", inventoryEntity.getTray());
							inventoryTolocUpdate.eq("box", inventoryEntity.getBox());

							InventoryEntity updateInventory = new InventoryEntity();
							updateInventory.setQty(BigDecimal.ZERO);
							updateInventory.setPickqty(BigDecimal.ZERO);
							updateInventory.setPutqty(BigDecimal.ZERO);
							inventoryDao.update(updateInventory, inventoryTolocUpdate);

							String tradekey = sequenceService.getSequence("trade");
							TradeEntity tradeEntity = new TradeEntity();

							tradeEntity.setTradekey(tradekey);
							tradeEntity.setTradetype(TradeConstant.TRADETYPE_PICK);
							tradeEntity.setSku(inventoryEntity.getSku());
							tradeEntity.setQty(inventoryEntity.getQty().negate());
							tradeEntity.setSourcetype(TradeConstant.SOURCETYPE_ORDERS);
							tradeEntity.setSourcekey(task_id + "");
							tradeEntity.setSourceline(null);
							tradeEntity.setSourcelinelist(null);
							tradeEntity.setFromlocation(inventoryEntity.getLocation());
							tradeEntity.setTolocation(StringUtils.EMPTY);
							tradeEntity.setFromtray(inventoryEntity.getTray());
							tradeEntity.setTotray(StringUtils.EMPTY);
							tradeEntity.setFrombox(inventoryEntity.getBox());
							tradeEntity.setTobox(StringUtils.EMPTY);
							tradeEntity.setFromlot(inventoryEntity.getLot());
							tradeEntity.setTolot(StringUtils.EMPTY);
							tradeEntity.setFromlot1(null);
							tradeEntity.setFromlot2(null);
							tradeEntity.setFromlot3("");
							tradeEntity.setFromlot4("");
							tradeEntity.setFromlot5("");
							tradeEntity.setFromlot6("");
							tradeEntity.setFromlot7("");
							tradeEntity.setFromlot8("");
							tradeEntity.setFromlot9("");
							tradeEntity.setFromlot10("");
							tradeEntity.setFromlot11("");
							tradeEntity.setFromlot12("");
							tradeEntity.setFromlot13("");
							tradeEntity.setFromlot14("");
							tradeEntity.setFromlot15("");
							tradeEntity.setTolot1(null);
							tradeEntity.setTolot2(null);
							tradeEntity.setTolot3("");
							tradeEntity.setTolot4("");
							tradeEntity.setTolot5("");
							tradeEntity.setTolot6("");
							tradeEntity.setTolot7("");
							tradeEntity.setTolot8("");
							tradeEntity.setTolot9("");
							tradeEntity.setTolot10("");
							tradeEntity.setTolot11("");
							tradeEntity.setTolot12("");
							tradeEntity.setTolot13("");
							tradeEntity.setTolot14("");
							tradeEntity.setTolot15("");
							tradeEntity.setRemark("WCS");
							tradeDao.insert(tradeEntity);
						}
					}

					UpdateWrapper<TaskEntity> updateTask = new UpdateWrapper<TaskEntity>();
					updateTask.eq("taskkey", TaskEntity.getTaskkey());

					//***********7这个时候刚给输送线，不能改9
//					if(taskstatus!=7){

						TaskEntity updateTaskEntity = new TaskEntity();
						updateTaskEntity.setTolocation(firsttolocation);
						updateTaskEntity.setStatus(TaskConstant.TASK_9);
						taskDao.update(updateTaskEntity, updateTask);
//					}


				}
//				if(taskstatus>=9){
					// 将任务记录写入备份库
					taskDao.insertRecord(map);
					// 删除WMS已做完的让你无
					taskDao.deleteWCSTask(map);
					txManager.commit(status);
//				}

			} catch (Exception e) {
				e.printStackTrace();
				txManager.rollback(status);
			}
		}
	}
}
